package com.bestcem.xm.award.grpc.client;

import com.bestcem.bp.grpc.v1.base.Code;
import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.qdes.grpc.v1.services.BpProjectServiceGrpc;
import com.bestcem.xm.qdes.grpc.v1.services.GetProjectTitleRequest;
import com.bestcem.xm.qdes.grpc.v1.services.GetProjectTitleResponse;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Service;
import zhongyan.xm.base.v1.Base;

/**
 * 问卷 grpc客户端
 *
 * @author sh.pei <sh.pei@idiaoyan.com>
 * @version v1.0
 * @date 2021/7/23 13:32
 */
@Slf4j
@Service
public class ProjectGrpcService {

    @GrpcClient(GrpcClientNames.DS_QDES)
    private BpProjectServiceGrpc.BpProjectServiceBlockingStub stub;

    /**
     * 查询项目名称
     *
     * @param request 请求数据
     * @return
     */
    public GetProjectTitleResponse getProjectTitle(GetProjectTitleRequest request) {
        try {
            return stub.getProjectTitle(request);
        } catch (Exception e) {
            log.error("[award] project getProjectTitle {} Error; ErrorMsg: {};", request, e.getMessage(), e);
            return GetProjectTitleResponse.newBuilder().setStatus(error("project服务调用失败")).build();
        }
    }

    /**
     * 查询项目名称
     *
     * @param projectId 项目id
     * @return
     */
    public ServiceResult<String> getProjectTitle(String projectId) {
        GetProjectTitleResponse titleResponse = getProjectTitle(GetProjectTitleRequest.newBuilder().setId(projectId).build());
        if (titleResponse == null) {
            return ServiceResult.fail("project服务调用失败");
        }
        if (titleResponse.getStatus().getCodeValue() != Code.OK_VALUE) {
            return ServiceResult.fail(titleResponse.getStatus().getMessage());
        }
        return ServiceResult.success(titleResponse.getTitle());
    }

    /**
     * 构造错误状态
     *
     * @param message 错误信息
     * @return
     */
    private Base.Status error(String message) {
        Base.Status.Builder status = Base.Status.newBuilder();
        status.setMessage(message);
        status.setCode(Base.Code.ERROR);
        return status.build();
    }
}
